package club.vann.nowcoder;

import java.util.Deque;
import java.util.LinkedList;
import java.util.Locale;

/**
 * <p>难度：Medium</p>
 * <p>题目：表达式求值</p>
 * <p>描述：请写一个整数计算器，支持加减乘三种运算和括号。
 * 示例1
 * 输入：
 * "1+2"
 * 复制
 * 返回值：
 * 3
 * 复制
 * 示例2
 * 输入：
 * "(2*(3-4))*5"
 * 复制
 * 返回值：
 * -10
 * 复制
 * 示例3
 * 输入：
 * "3+2*3*4-1"
 * 复制
 * 返回值：
 * 26</p>
 * @author vann
 * @Title:
 * @Description:
 * @date 2021/6/18 10:58
 */
public class NC137 {
    public static void main(String[] args) {
        NC137 nc = new NC137();

        System.out.println("Result["+TestCase.ANS+"] : " + nc.solve(TestCase.S));
        System.out.println("Result["+TestCase.ANS1+"] : " + nc.solve(TestCase.S1));
        System.out.println("Result["+TestCase.ANS2+"] : " + nc.solve(TestCase.S2));
    }

    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     * 返回表达式的值
     * @param s string字符串 待计算的表达式
     * @return int整型
     */
    public int solve (String s) {
        // write code here
        LinkedList<Integer> stack = new LinkedList<>();
        char preSign = '+';
        int num = 0;
        char[] ch = s.toCharArray();
        int len = ch.length;

        for(int i = 0; i < len; i ++) {
            if(ch[i] == ' ') {
                continue;
            }

            if(Character.isDigit(ch[i])) {
                num = num * 10 + (ch[i]-'0');
            }

            if(ch[i] == '('){
                int j = i + 1;
                int counterPartition = 1;
                while (counterPartition > 0) {
                    if (ch[j] == '(') {
                        counterPartition++;
                    }
                    if (ch[j] == ')') {
                        counterPartition--;
                    }
                    j++;
                }
                num = solve(s.substring(i + 1, j - 1));
                i = j - 1;
            }

            if (!Character.isDigit(ch[i]) || i == len - 1) {
                if (preSign == '+') {
                    stack.push(num);
                } else if (preSign == '-') {
                    stack.push(-1 * num);
                } else if (preSign == '*') {
                    stack.push(stack.pop() * num);
                } else if (preSign == '/') {
                    stack.push(stack.pop() / num);
                }
                num = 0;
                preSign = ch[i];
            }

        }

        int ans = 0;
        while(!stack.isEmpty()) {
            ans += stack.pop();
        }
        return ans;
    }

    static class TestCase {
        public static int ANS = -10;
        public static String S = "(2*(3-4))*5";

        public static int ANS1 = 26;
        public static String S1 = "3+2*3*4-1";

        public static int ANS2 = 3;
        public static String S2 = "1+2";
    }
}
